import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:safetymonitor/app/components/custom_date_type.dart';
import 'package:safetymonitor/app/components/custom_modele/custom_dropdown_selection.dart';
import 'package:safetymonitor/app/core/core.dart';
import 'package:safetymonitor/app/core/ext/time.dart';
import 'package:safetymonitor/app/core/http/http.dart';
import 'package:safetymonitor/app/core/utils/interface.dart';
import 'package:safetymonitor/app/core/utils/user_manager.dart';
import 'package:safetymonitor/app/data/common/chart_data.dart';
import 'package:safetymonitor/app/data/entities/home/monitor/safe_real_time_monitor_page_entity.dart';
import 'package:syncfusion_flutter_charts/charts.dart';

part 'iface.dart';

part 'misc.dart';

final class HomeSafetyMonitor extends StatefulWidget {
  const HomeSafetyMonitor({super.key});

  @override
  State<HomeSafetyMonitor> createState() => _HomeSafetyMonitorState();
}

class _HomeSafetyMonitorState extends State<HomeSafetyMonitor>  with WidgetsBindingObserver{
  final _tabIdx = ValueNotifier(0);

  @override
  void initState() {
    // _getRealTimeAlarm();
    _getAlarmHistory();
     WidgetsBinding.instance.addObserver(this);
    super.initState();
  }
  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _getRealTimeAlarm();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    if(state==AppLifecycleState.resumed){
      //后台到前台调用1次
      // _getRealTimeAlarm();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      // padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
      child: Column(
        children: [
          // Padding(padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 0), child: _buildTop()),
          // AppGaps.vGap10,
          // _buildSwitch(),
          ValueListenableBuilder(
            valueListenable: _tabIdx,
            builder: (_, tabIdx, __) => switch (tabIdx) {
              0 => _buildRealTime(),
              1 => ListenableBuilder(
                  listenable: _alarmData,
                  builder: (_, __) {
                    return _buildAlarm();
                  },
                ),
              final val => Center(child: Text(val.toString())),
            },
          ),
          AppGaps.vGap60,
          AppGaps.vGap10,
        ],
      ),
    );
  }

  /// 顶部报警数
  // Widget _buildTop() {
  //   return Row(
  //     children: [
  //       SvgPicture.asset('assets/svg/icon_blue_alarm.svg'),
  //       AppGaps.hGap6,
  //       Text('今日报警数', style: TextStyle(fontSize: 16.w)),
  //       const Spacer(),
  //       ListenableBuilder(
  //         listenable: _alarmCount,
  //         builder: (_, __) {
  //           return Text(
  //             _alarmCount.value.toString(),
  //             style: TextStyle(
  //               fontWeight: FontWeight.w500,
  //               fontSize: 16.w,
  //               color: const Color(0xff3D4769),
  //             ),
  //           );
  //         },
  //       ),
  //     ],
  //   );
  // }

  /// 切换实时与历史
  Widget _buildSwitch() {
    return Row(
      children: [
        _buildSwitchItem('实时监测数据', 0),
        AppGaps.hGap6,
        _buildSwitchItem('报警统计', 1),
        const Spacer(),
        ValueListenableBuilder(
          valueListenable: _tabIdx,
          builder: (_, val, __) {
            if (val == 0) return const SizedBox();
            return SizedBox(
              width: 77.w,
              height: 32.w,
              child: ValueListenableBuilder(
                valueListenable: _alarmInterval,
                builder: (_, val, __) {
                  return CustomDropdownSelection(
                    hintText: '请选择周期',
                    text: _alarmInterval.value.title,
                    onCallBack: _showIntervalPicker,
                  );
                },
              ),
            );
          },
        ),
      ],
    );
  }

  Widget _buildSwitchItem(String title, int idx) {
    return ValueListenableBuilder(
      valueListenable: _tabIdx,
      builder: (_, tabIdx, __) => GestureDetector(
        onTap: () => _tabIdx.value = idx,
        child: Container(
          padding: const EdgeInsets.symmetric(horizontal: 9, vertical: 5),
          decoration: BoxDecoration(
            color: tabIdx == idx ? const Color(0xff1847E3) : const Color(0xffEBECF3),
            borderRadius: BorderRadius.circular(9.w),
          ),
          child: Text(
            title,
            style: TextStyle(
              color: tabIdx == idx ? Colors.white : Colors.black,
            ),
          ),
        ),
      ),
    );
  }

  /// 实时数据
  Widget _buildRealTime() {
    return ValueListenableBuilder(
      valueListenable: _realTimeData,
      builder: (_, val, __) {
        return Expanded(
          child: val.isNotEmpty
              ? ListView.builder(
                  padding: EdgeInsets.only(top: 0.w, bottom: 100.w),
                  itemCount: val.length,
                  itemBuilder: (_, idx) => _buildRealTimeItem(val[idx]),
                )
              : Center(
                  child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    SvgPicture.asset('assets/svg/zhiban_empty_bg.svg'),
                    Text(
                      '暂无内容',
                      style: TextStyle(
                        color: const Color(0xFFC7CEE5),
                        fontSize: 14.sp,
                      ),
                    ),
                  ],
                )),
        );
      },
    );
  }

  Widget _buildRealTimeItem(SafeRealTimeMonitorPageEntity data) {
    return Container(
      decoration: BoxDecoration(
        gradient: const LinearGradient(
          colors: [Color(0xffF9FBFF), Colors.white],
          begin: Alignment.centerLeft,
          end: Alignment.centerRight,
        ),
        border: Border(
          bottom: BorderSide(
            color: const Color(0xffE2E8FD),
            width: 1.w,
          ),
        ),
      ),
      padding: EdgeInsets.symmetric(vertical: 10.w, horizontal: 17.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            data.companyName ?? '',
            style: TextStyle(
              color: const Color(0xff3F425B),
              fontSize: 13.w,
              fontWeight: FontWeight.w500,
            ),
          ),
          AppGaps.vGap10,
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Row(
                children: [
                  Text(
                    '点位：',
                    style: TextStyle(
                      color: const Color(0xffC7CEE5),
                      fontSize: 13.w,
                    ),
                  ),
                  Text(
                    data.point ?? '',
                    style: TextStyle(
                      color: const Color(0xff1D3452),
                      fontSize: 13.w,
                    ),
                  ),
                ],
              )._wrapSized,
              Row(
                children: [
                  Text(
                    '报警类型：',
                    style: TextStyle(
                      color: const Color(0xffC7CEE5),
                      fontSize: 13.w,
                    ),
                  ),
                  Text(
                    _getAlarmType(data.alarmType ?? 0),
                    style: TextStyle(
                      color: const Color(0xff1D3452),
                      fontSize: 13.w,
                    ),
                  ),
                ],
              )._wrapSized,
            ],
          ),
          AppGaps.vGap10,
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Row(
                children: [
                  Text(
                    '报警数值：',
                    style: TextStyle(
                      color: const Color(0xffC7CEE5),
                      fontSize: 13.w,
                    ),
                  ),
                  Text(
                    data.val.toString(),
                    style: TextStyle(
                      color: const Color(0xff1D3452),
                      fontSize: 13.w,
                    ),
                  ),
                ],
              )._wrapSized,
              Row(
                children: [
                  Text(
                    '报警级别：',
                    style: TextStyle(
                      color: const Color(0xffC7CEE5),
                      fontSize: 13.w,
                    ),
                  ),
                  Text(
                    _getAlarmLevel(data.alarmLevel ?? 0),
                    style: TextStyle(
                      color: const Color(0xff1D3452),
                      fontSize: 13.w,
                    ),
                  ),
                ],
              )._wrapSized,
            ],
          ),
          AppGaps.vGap10,
          Row(
            children: [
              Text(
                '报警时间：',
                style: TextStyle(
                  color: const Color(0xffC7CEE5),
                  fontSize: 13.w,
                ),
              ),
              Text(
                DateTime.fromMillisecondsSinceEpoch(int.tryParse(data.alarmStartTime ?? '0') ?? 0).toStr,
                style: TextStyle(
                  color: const Color(0xff1D3452),
                  fontSize: 13.w,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  /// 报警数据
  Widget _buildAlarm() {
    if (_alarmData.value.isEmpty) {
      return Center(
          child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          SvgPicture.asset('assets/svg/zhiban_empty_bg.svg'),
          Text(
            '暂无内容',
            style: TextStyle(
              color: const Color(0xFFC7CEE5),
              fontSize: 14.sp,
            ),
          ),
        ],
      ));
    }
    return Row(
      children: [
        SizedBox(
          width: 128.w,
          height: 128.w,
          child: _buildAlarmChart(),
        ),
        const Spacer(),
        SizedBox(
          height: 128.w,
          width: 118.w,
          child: ListView(
            padding: EdgeInsets.zero,
            children: List.generate(
              _alarmData.value.length,
              (index) => _buildAlarmListItem(_alarmData.value.elementAt(index)),
            ).toList(),
          ),
        ),
        AppGaps.hGap20,
      ],
    ).paddingOnly(top: 10.w);
  }

  /// 报警记录表
  Widget _buildAlarmChart() {
    return Stack(
      alignment: Alignment.center,
      children: [
        SfCircularChart(
          series: <CircularSeries>[
            DoughnutSeries<ChartData, String>(
              dataSource: _alarmData.value,
              pointColorMapper: (ChartData data, _) => data.color,
              xValueMapper: (ChartData data, _) => data.x,
              yValueMapper: (ChartData data, _) => data.y,
              name: '报警信息',
              dataLabelSettings: const DataLabelSettings(
                isVisible: false,
                labelPosition: ChartDataLabelPosition.inside,
              ),
              radius: '100%',
              innerRadius: '75%',
              enableTooltip: true,
            ),
          ],
          annotations: [
            if (_alarmData.value.isEmpty)
              CircularChartAnnotation(
                widget: AnimatedOpacity(
                  opacity: 1,
                  duration: Durations.medium1,
                  child: SizedBox(
                    width: 87.w,
                    height: 87.w,
                    child: CircularProgressIndicator(
                      strokeWidth: 11.w,
                      value: 1,
                      valueColor: AlwaysStoppedAnimation(_alarmData.value.firstOrNull?.color ?? Colors.blue),
                    ),
                  ),
                ),
              ),
          ],
        ),
        Column(
          mainAxisAlignment: MainAxisAlignment.center,
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(
              _alarmData.value.total.toString(),
              style: TextStyle(
                fontSize: 17.w,
                fontWeight: FontWeight.w500,
              ),
            ),
            Text(
              '总数',
              style: TextStyle(color: Colors.grey, fontSize: 13.w),
            )
          ],
        )
      ],
    );
  }

  /// 报警数据右侧每个公司的数据
  Widget _buildAlarmListItem(ChartData data) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 3.w),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Container(
            width: 10.w,
            height: 10.w,
            decoration: BoxDecoration(
              color: data.color,
              borderRadius: BorderRadius.circular(2.w),
            ),
          ),
          AppGaps.hGap10,
          SizedBox(
            width: 85.w,
            child: Text(
              data.x,
              style: TextStyle(
                fontSize: 13.w,
                color: const Color(0xff1D3452),
              ),
            ),
          ),
          Text(
            data.y.toString(),
            style: TextStyle(
              fontSize: 13.w,
              color: const Color(0xff1D3452),
            ),
          ),
        ],
      ),
    );
  }
}
